package com.aoxin.service.impl.course.webCourse;

import java.io.File;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;

import com.aoxin.util.ageUtils.ChildrenAgeUtil;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.aoxin.mapper.SlfChildExpectedTimeMapper;
import com.aoxin.mapper.course.webCourse.SlfChildrenMapper;
import com.aoxin.mapper.opm.SlfUserMapper;
import com.aoxin.model.SlfChildExpectedTime;
import com.aoxin.model.course.SlfChildren;
import com.aoxin.model.dto.SelectDto;
import com.aoxin.model.opm.SlfUser;
import com.aoxin.service.inter.course.webCourse.ChildrenService;
import com.aoxin.util.AESUtil;
import com.aoxin.util.CommonUtil;
import com.aoxin.util.ErrorUtil;
import com.aoxin.util.OSSUtils;
import com.aoxin.util.RedisUtil;
import com.aoxin.util.ThreadLocalUtil;
import com.aoxin.util.qrcode.QRCode;


@Service
public class ChildrenServiceImpl implements ChildrenService {

	@Autowired
	private SlfChildrenMapper slfChildrenMapper;

	@Autowired
	private SlfUserMapper slfUserMapper;
	
	@Autowired
	private SlfChildExpectedTimeMapper slfChildExpectedTimeMapper;

	@Override
	@Transactional
	public Integer deleteByChildrenId(Integer childrenId) {
		Integer result = 0;
		if (childrenId != null) {
			result = slfChildrenMapper.deleteByChildrenId(childrenId);
		}
		return result;
	}

	@Override
	@Transactional
	public Integer insertChildren(SlfChildren slfChildren,String parameter) throws ParseException {
		Assert.notNull(slfChildren, String.format(ErrorUtil.PARAMETER_NULL, "slfChildren"));
		Integer result = 0;
		SlfChildren cl=new SlfChildren();
		cl.setUserId(ThreadLocalUtil.getUser().getUserId());
		List<SlfChildren> slfList=slfChildrenMapper.getChildren(cl);
		// 计算年龄
		try{
			slfChildren.setAge(ChildrenAgeUtil.getAge(slfChildren.getBirthday()));
			if(null == slfChildren.getUserId()){
				slfChildren.setUserId(ThreadLocalUtil.getUser().getUserId());
				slfChildren.setUserName(ThreadLocalUtil.getUser().getName());
			}else{
				SlfUser slfUser = this.slfUserMapper.selectByPrimaryKey(slfChildren.getUserId());
				slfChildren.setUserName(slfUser.getName());
			}
			Integer check = this.slfChildrenMapper.checkChildren(ThreadLocalUtil.getUser().getUserId());
			if(check == 0){
				slfChildren.setSequence(0);
			}
			result = this.slfChildrenMapper.insertChildren(slfChildren);
			// 生成二维码
			QRCode qrCode = new QRCode();
			String imgPath = CommonUtil.getFilePath() + File.separator + slfChildren.getName() + slfChildren.getChildrenId() + ".png";
			qrCode.encoderQRCode(AESUtil.encrypt(slfChildren.getChildrenId().toString(), AESUtil.PASSWORD), imgPath, "png", 9);
			// 上传值OSS
			File file = new File(imgPath);
			String path = OSSUtils.upload(file);
			file.delete();
			slfChildren.setChildrenQrCode(path);
			String schoolName= slfUserMapper.querySchoolName(slfChildren.getSchoolId());
			slfChildren.setSchoolName(schoolName);
			this.slfChildrenMapper.updateChildren(slfChildren);
			//增加期望时间
			Integer maxId = slfChildrenMapper.getChildrenIdMax();
			if(parameter!=null){
				String[] ptArray = parameter.split(",");
				if(null != parameter) {
					for(String parameters : ptArray){
						SlfChildExpectedTime slfChildExpectedTime = new SlfChildExpectedTime();
						parameters = parameters.replaceAll("/",",");
						slfChildExpectedTime.setChildrenId(maxId);
						slfChildExpectedTime.setExpectedTime(parameters);
						slfChildExpectedTime.setFlag(0);
						slfChildExpectedTimeMapper.insertSelective(slfChildExpectedTime);
					}
				}
			}
			//用户第一次填写孩子赠送40立方比
			if(slfList==null || slfList.size()==0){
				//新建用户 
				SlfUser slfUser=ThreadLocalUtil.getUser();
	            slfUser.setLfb(slfUser.getLfb()+40);
				Integer update = this.slfUserMapper.updateByPrimaryKeySelective(slfUser);
				SlfChildren oldslfChildren = (SlfChildren) RedisUtil.get(slfUser.getPhone() + slfUser.getUserId() + ChildrenService.REDIS_CHILDREN_CODE);
				if(update>0){
					result=2;
				}else{
					throw new IllegalAccessException(ErrorUtil.CHILDREN_ERROR);
				}
				if (null != oldslfChildren) {
					RedisUtil.del(slfUser.getPhone() + slfUser.getUserId() + ChildrenService.REDIS_CHILDREN_CODE);
				}
				SlfChildren slone=  new SlfChildren();
				slone.setUserId(ThreadLocalUtil.getUser().getUserId());
				List<SlfChildren>   slfChildrenList=slfChildrenMapper.getChildren(slone);
	            RedisUtil.set(slfUser.getPhone() + slfUser.getUserId() + ChildrenService.REDIS_CHILDREN_CODE, slfChildrenList.get(0));
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public List<SlfChildren> getChildren(SlfChildren slfChildren) {
		List<SlfChildren> slfChildrenList = slfChildrenMapper.getChildren(slfChildren);
		return slfChildrenList;
	}

	@Override
	public SlfChildren getAChildren(Integer childrenId) {
		SlfChildren slfChildren = new SlfChildren();
		if (childrenId != null) {
			slfChildren = slfChildrenMapper.getAChildren(childrenId);
		}
		return slfChildren;
	}

	@Override
	@Transactional
	public Integer updateChildren(SlfChildren slfChildren,String parameter) throws ParseException {
		Assert.notNull(slfChildren, String.format(ErrorUtil.PARAMETER_NULL, "slfChildren"));
		Integer result = 0;
		String age = ChildrenAgeUtil.getAge(slfChildren.getBirthday());
		System.out.println("====================================="+age);
		slfChildren.setAge(age);
		result = slfChildrenMapper.updateChildren(slfChildren);
		// 同步缓存
		SlfUser user = ThreadLocalUtil.getUser();
		if("1".equals(RedisUtil.get(user.getPhone() + user.getUserId() + ChildrenService.REDIS_CHILDREN_CODE).toString())){
			RedisUtil.del(user.getPhone() + user.getUserId() + ChildrenService.REDIS_CHILDREN_CODE);
			RedisUtil.set(user.getPhone() + user.getUserId() + ChildrenService.REDIS_CHILDREN_CODE, slfChildren);
		}
		//TODO 为啥更改孩子信息后存的是返回值
		SlfChildren oldslfChildren = (SlfChildren) RedisUtil.get(user.getPhone() + user.getUserId() + ChildrenService.REDIS_CHILDREN_CODE);
		if (null != oldslfChildren) {
			RedisUtil.del(user.getPhone() + user.getUserId() + ChildrenService.REDIS_CHILDREN_CODE);
			RedisUtil.set(user.getPhone() + user.getUserId() + ChildrenService.REDIS_CHILDREN_CODE, slfChildren);
		}
		if(null != parameter) {
			this.slfChildExpectedTimeMapper.deleteTimeByChildrenId(slfChildren.getChildrenId());
			String[] parameterArray = parameter.split(",");
			for(String parameters : parameterArray){
				SlfChildExpectedTime slfChildExpectedTime = new SlfChildExpectedTime();
				parameters = parameters.replaceAll("/",",");
				slfChildExpectedTime.setChildrenId(slfChildren.getChildrenId());
				slfChildExpectedTime.setExpectedTime(parameters);
				slfChildExpectedTime.setFlag(0);
				slfChildExpectedTimeMapper.insertSelective(slfChildExpectedTime);
			}
		}
		return result;
	}

	@Override
	public List<SlfChildren> getChildrenInfo(Integer userId) {
		List<SlfChildren> slfChildrenList = new ArrayList<>();
		if (userId != null) {
			SlfChildren slfChildren = new SlfChildren();
			slfChildren.setUserId(userId);
			slfChildrenList = slfChildrenMapper.getChildren(slfChildren);
		}
		return slfChildrenList;
	}

	@Override
	@Transactional
	public Integer updateChildrenSchool(Integer childrenId, String schoolName) {
		Integer result = 0;
		if (childrenId != null && schoolName != null && !"".equals(schoolName)) {
			result = slfChildrenMapper.updateChildrenSchool(childrenId, schoolName);
		}
		return result;
	}

	@Override
	public List<SelectDto> getChildrenIdName() {
		List<SelectDto> selectDtoList = slfChildrenMapper.getChildrenIdName();
		return selectDtoList;
	}

	@Override
	public Integer getDefaultChildrenId(Integer userId) {
		Integer childrenId = slfChildrenMapper.getDefaultChildrenId(userId);
		return childrenId;
	}

	/**
	 * 计算年龄
	 * 
	 * @param date
	 *            生日
	 * @return 年龄
	 * @throws ParseException 
	 */
	private int getAge(Date date) throws ParseException {
		int age = 0;
		if (null != date) {
			Calendar cal = Calendar.getInstance();
			int yearNow = cal.get(Calendar.YEAR);
			int monthNow = cal.get(Calendar.MONTH)+1;
			int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
		
			cal.setTime(date);
			int yearBirth = cal.get(Calendar.YEAR);
			int monthBirth = cal.get(Calendar.MONTH);
			int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

			age = yearNow - yearBirth;
			if (monthNow <= monthBirth) {
				if (monthNow == monthBirth) {
					if (dayOfMonthNow < dayOfMonthBirth)
						age--;
				} else {
					age--;
				}
			}
		}
		return age;
	}


	@Override
	public List<Integer> getChildrenId(Integer userId) {
		List<Integer> childrenIdList = new ArrayList<>();
		if (userId != null) {
			childrenIdList = slfChildrenMapper.getChildrenId(userId);
		}
		return childrenIdList;
	}

	@Override
	public void updateDefaultChildren(Integer childrenId, Integer userId) {
		if (childrenId != null) {
			slfChildrenMapper.updateDefaultChildren(childrenId, userId);
		}
	}

	@Override
	public void recoverChildren(Integer childrenId, Integer userId) {
		if (childrenId != null) {
			slfChildrenMapper.recoverChildren(childrenId, userId);
		}
	}

	@Override
	public List<SlfChildren> surplusClassHour() {
		
		Integer userId=ThreadLocalUtil.getUser().getUserId();
		SlfChildren slfChildren=new SlfChildren();
		slfChildren.setUserId(userId);
		slfChildren.setChildrenId(ThreadLocalUtil.getChildren().getChildrenId());
		List<SlfChildren> childrenList=slfChildrenMapper.getChildren(slfChildren);
		DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
		for (int j = 0,c=childrenList.size(); j < c; j++) {
			List<Map<String,Object>> surplusClassHourListMap=new ArrayList<Map<String,Object>>();
			Integer childrenId=	childrenList.get(j).getChildrenId();
			String childrenName=childrenList.get(j).getName();
			//查询B类剩余课程 
			List<Map<String,Object>>	surplusClassHourBListMap=this.slfChildrenMapper.queryChildrenSurplusClassHourB(childrenId);
		
			for (int i = 0,b=surplusClassHourBListMap.size(); i < b; i++) {
			String endTime= DateTime.parse(surplusClassHourBListMap.get(i).get("employ_time").toString(),format).toString("HH:mm:ss");
			surplusClassHourBListMap.get(i).put("endTime", endTime);
			String startTime=DateTime.parse( surplusClassHourBListMap.get(i).get("employ_time").toString(),format).minusHours(1).toString("yyyy-MM-dd HH:mm:ss");
			surplusClassHourBListMap.get(i).put("startTime", startTime);
			surplusClassHourBListMap.get(i).put("childrenName", childrenName);
			surplusClassHourListMap.add(surplusClassHourBListMap.get(i));
			}
			//查询C类剩余课程
			List<Map<String,Object>>	surplusClassHourCListMap=this.slfChildrenMapper.queryChildrenSurplusClassHourC(childrenId);
			for (int i = 0,b=surplusClassHourCListMap.size(); i < b; i++) {
			String 	startTime= DateTime.parse( surplusClassHourCListMap.get(i).get("course_startTime").toString(),format).toString("yyyy-MM-dd HH:mm:ss");
			surplusClassHourCListMap.get(i).put("startTime", startTime);
			String 	endTime= DateTime.parse( surplusClassHourCListMap.get(i).get("course_startTime").toString(),format).plusHours(1).toString("HH:mm:ss");
			surplusClassHourCListMap.get(i).put("endTime", endTime);
			surplusClassHourCListMap.get(i).put("childrenName", childrenName);
			surplusClassHourListMap.add(surplusClassHourCListMap.get(i));
			}
			childrenList.get(j).setSurplusClassHourList(surplusClassHourListMap);
		}
		return childrenList;
	}
}
